<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div class="flex justify-around w-1/3 m-auto mb-2" v-if="isSelected">
      <a-button @click="handleResetFields">重置</a-button>
      <a-button type="primary" @click="customSubmitFunc" class="ml-2">保存</a-button>
    </div>
    <BasicForm @register="registerForm" v-show="isSelected">
      <template #condValue="{ model, field }">
        <FormItemRest>
          <div class="flex justify-between">
            <Select
              v-model:value="dataRef['fields']"
              show-search
              placeholder="请选择"
              style="width: 33%"
              :options="mockData"
              :field-names="{ label: 'title', value: 'name' }"
              optionFilterProp="title"
              :filter-option="filterOption"
              allow-clear
            />
            <Select
              v-model:value="dataRef['compare']"
              show-search
              placeholder="请选择"
              style="width: 30%"
              :options="compareList"
              :filter-option="filterOption"
              allow-clear
            />
            <Input style="width: 100px !important" v-model:value="model[field]" />
          </div>
          <div> 当为等号时，如果有多个满足条件的值可以用逗号分隔， 空表示为默认条件 </div>
        </FormItemRest>
      </template>

      <template #deptNamesSlot>
        <FormItemRest>
          <InputTextArea v-model:value="dataRef['deptNames']" :disabled="true" />
          <div class="mt-2">
            <a-button type="primary" @click="handleSelect(1)">选择</a-button>
            <a-button @click="handleSelectClear(1)" class="ml-2">清空</a-button>
          </div>
        </FormItemRest>
      </template>
      <template #imgComb>
        <a-button type="primary" @click="handleConfiguration">配置</a-button>
      </template>

      <template #nodeScript>
        <FormItemRest>
          <AceEditor
            v-model:modelValue="dataRef['deptNames']"
            :isReadonly="isScriptEditable > 0"
            style="height: 200px"
          />
          <a-button
            class="mt-2"
            type="primary"
            @click="handleDesignIframe"
            :disabled="isScriptEditable == 2"
            >设计器</a-button
          >
          <a-button @click="handleSelectClear(1)" class="ml-2">清空</a-button>
        </FormItemRest>
      </template>
    </BasicForm>
    <div class="h-300px flex items-center justify-center" v-if="!isSelected">
      <Empty :image="simpleImage" description="请选择节点" />
    </div>
    <SelectRoleModal @register="registerModalSelectRole" @success="handleSuccessSelectRole" />
    <ConfigrationCombinationModal
      @register="registerModalConfigrationCombination"
      @success="handleSuccessConfigrationCombination"
    />
    <DesignIframe
      @register="registerModalDesignIframe"
      @success="handleSuccessDesignIframe"
      ref="ifrmRef"
    />
  </ScrollContainer>
</template>

<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { ref, watchEffect, onUnmounted, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { ScrollContainer } from '/@/components/Container';
  import { formSchemaLine } from './nodeEdit.data';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Select, Empty, Form, InputNumber, Input } from 'ant-design-vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useFlowStore } from '/@/store/modules/flow';
  import {
    getFormGetFields,
    getMyflowGenerateWorkflowString,
    getAdminUpdateWorkflowProps,
  } from '/@/api/flowManage/flowManage';

  import { isArray } from '/@/utils/is';
  import SelectRoleModal from './modules/SelectRoleModal.vue';
  import { useModal } from '/@/components/Modal';

  import ConfigrationCombinationModal from './modules/configrationCombination/ConfigrationCombinationModal.vue';
  import { WorkflowLinkDb } from '/@/enums/flowManage';
  import { cloneDeep } from 'lodash-es';
  import { DesignIframe } from '/@/views/system/workflow/flowManagement/modules/flowPicture/modules/modules/index';
  import { AceEditor } from '/@/components/AceEditor/index';
  import { useUserStore } from '/@/store/modules/user';
  import { getRoleNames } from '/@/api/system/system';

  const FormItemRest = Form.ItemRest;
  const InputTextArea = Input.TextArea;
  const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  const { t } = useI18n();
  const { createMessage } = useMessage();
  const props = defineProps({
    formCode: {
      type: String as PropType<string>,
      default: '',
    },
  });
  const emits = defineEmits(['success']);
  const loading = ref(false);
  const dataRef: any = ref({});
  const useFlow = useFlowStore();
  const isSelected = ref(false);
  const isScriptEditable = ref(0);
  const userStore = useUserStore();

  watchEffect(() => {
    const obj = cloneDeep(useFlow.currentFlowData);
    isSelected.value = false;
    if (obj && Object.keys(obj).length) {
      isSelected.value = true;
      setTimeout(() => {
        fetch(obj);
      });
    }

    let serverInfo = userStore.getServerInfo;
    isScriptEditable.value = serverInfo.isScriptEditable;
    console.log('isScriptEditable', isScriptEditable.value);
  });

  let formdata = {};

  const submitDesigner = async () => {
    let myflow = $.myflow;
    console.log('myflow', myflow);
    let flowJson = myflow.getJson();
    let flowString = ''; //myflow.getWorkflow();
    const serverName = window.location.hostname;
    const flowStringRecord = await getMyflowGenerateWorkflowString({
      flowJson: flowJson,
      serverName: serverName,
    });
    flowString = flowStringRecord.flowString;
    console.log('flowJson', flowJson);
    console.log('flowString', flowString);
    // console.log("myflow.getWorkflow()=" + flowString);
    // let op = o('op').value;
    // let op = formdata['op'];
    // let url = op == 'edit' ? 'modifyFlowPredefined' : 'createFlowPredefined';
    console.log('useflow', useFlow);
    console.log('formdata', formdata);
    const flowEdit = useFlow.flowEdit;
    const form = {
      op: flowEdit['op'],
      title: flowEdit['title'],
      dirCode: flowEdit['dirCode'],
      examine: flowEdit['examine'],
      id: flowEdit['id'],
      flowString: flowString,
      flowJson: flowJson,
      typeCode: flowEdit['typeCode'],
      returnBack: flowEdit['returnBack'],
      isReactive: flowEdit['isReactive'] ? '1' : '0',
      isRecall: flowEdit['isRecall'] ? '1' : '0',
      returnMode: flowEdit['returnMode'],
      returnStyle: flowEdit['returnStyle'],
      roleRankMode: flowEdit['roleRankMode'],
      props: flowEdit['props'],
      views: flowEdit['views'],
      isDistribute: flowEdit['isDistribute'] ? '1' : '0',
      toghterCondition: formdata['hiddenCondition'],
      msgProp: flowEdit['msgProps'], // 注意得传msgProp
      isPlus: flowEdit['isPlus'] ? '1' : '0',
      isTransfer: flowEdit['isTransfer'] ? '1' : '0',
      isReply: flowEdit['isReply'] ? '1' : '0',
      isModuleFilter: flowEdit['isModuleFilter'] ? '1' : '0',
      downloadCount: flowEdit['downloadCount'],
      canDelOnReturn: flowEdit['canDelOnReturn'] ? '1' : '0',
      startMode: !flowEdit['startMode'] ? '1' : flowEdit['startMode'],
      rules: isArray(flowEdit['rules']) ? JSON.stringify(flowEdit['rules']) : flowEdit['rules'],
    };
    console.log('form', form);
    const res = await getAdminUpdateWorkflowProps(form);
    // location.reload();
    emits('success');
    // emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    createMessage.success('操作成功');
  };
  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate, getFieldsValue }] =
    useForm({
      labelWidth: 70,
      schemas: formSchemaLine, //formSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 23,
      },
      labelWrap: true,
      // submitFunc: void customSubmitFunc,
    });

  const fetch = async (obj) => {
    await nextTick();
    dataRef.value = { ...obj };
    console.log('obj', obj);
    resetFields();

    getDataList();
    console.log('dataRef.value1', dataRef.value);
    try {
      if (
        unref(dataRef).depts &&
        !isArray(unref(dataRef).depts) &&
        unref(dataRef)['conditionType'] == WorkflowLinkDb.COND_TYPE_ROLE
      ) {
        console.log('test 123');
        const res = await getRoleNames({ codes: dataRef.value['depts'] });
        if (isArray(res)) {
          dataRef.value['deptNames'] = res.join(',');
        }
      }
    } catch (err) {}

    dataRef.value.deptNames = decodeLinkStr(dataRef.value.deptNames);
    console.log('dataRef.value2', dataRef.value);
    setFieldsValue({ ...dataRef.value });
    updateSchema([
      {
        field: 'desc',
        componentProps: {
          onChange: (e) => {
            SetSelectedLinkProperty('desc', e.target.value);
          },
        },
      },
    ]);
    updateSchema([
      {
        field: 'expireHour',
        componentProps: {
          onChange: (e) => {
            SetSelectedLinkProperty('expireHour', e.target.value);
          },
        },
      },
    ]);
  };
  const handleResetFields = () => {
    resetFields();
  };
  const mockData = ref<Recordable[]>([]);
  const getDataList = async () => {
    let params = {
      formCode: props.formCode,
    };
    await getFormGetFields(params).then((res) => {
      let data = res || [];
      data.forEach((item) => {
        item.key = item.name;
        item.description = item.title;
        delete item.options;
      });
      mockData.value = data;
      console.log('mockData.value', mockData.value);
    });
  };
  //   watch(
  //     () => props.formCode,
  //     (newVal) => {
  //       console.log('newVal', newVal);
  //       if (newVal) {
  //         getDataList();
  //       }
  //     },
  //     {
  //       immediate: true,
  //     },
  //   );

  const compareList = ref([
    {
      value: '>=',
      label: '>=',
    },
    {
      value: '<=',
      label: '<=',
    },
    {
      value: '>',
      label: '>',
    },
    {
      value: '<',
      label: '<',
    },
    {
      value: '=',
      label: '=',
    },
    {
      value: '<>',
      label: '<>',
    },
  ]);

  //线的保存逻辑
  const customSubmitFunc = async () => {
    try {
      const values = await validate();
      formdata = Object.assign({}, dataRef.value, values);
      for (let v in formdata) {
        if (formdata[v] == null || formdata[v] == undefined) {
          formdata[v] = '';
        }
      }
      console.log('formdata-PathEdit', formdata);
      SetSelectedLinkProperty('conditionType', formdata['conditionType']);
      SetSelectedLinkProperty('desc', formdata['desc']);
      SetSelectedLinkProperty('expireHour', formdata['expireHour']);
      SetSelectedLinkProperty('expireAction', formdata['expireAction']);
      var t = '';
      if (formdata['conditionType'] == WorkflowLinkDb.COND_TYPE_FORM) {
        t =
          (formdata['fields'] ? formdata['fields'] : '') +
          (formdata['compare'] ? formdata['compare'] : '') +
          (formdata['condValue'] ? formdata['condValue'] : '');
      } else if (
        formdata['conditionType'] ==
        (WorkflowLinkDb.COND_TYPE_DEPT || WorkflowLinkDb.COND_TYPE_DEPT_BELONG)
      ) {
        t = isArray(formdata['depts']) ? formdata['depts'].join(',') : formdata['depts'];
      } else if (formdata['conditionType'] == WorkflowLinkDb.COND_TYPE_ROLE) {
        t = isArray(formdata['depts']) ? '' : formdata['depts'];
      } else if (formdata['conditionType'] == WorkflowLinkDb.COND_TYPE_SCRIPT) {
        t = formdata['deptNames'] ? formdata['deptNames'].trim() : '';
      }
      SetSelectedLinkProperty('title', encodeLinkStr(t));

      submitDesigner();
    } catch (err) {
      console.error(err);
    }
  };
  //@task: 注意在控件的link中不能存储"号
  function encodeLinkStr(str) {
    console.log('str', str);
    if (!str) return '';
    if (!str.trim()) return '';
    str = str.replaceAll(':', '\\colon');
    str = str.replaceAll(';', '\\semicolon');
    str = str.replaceAll(',', '\\comma');
    str = str.replaceAll('\r\n', '\\newline');
    str = str.replaceAll('\n', '\\newline'); // textarea中的换行是\n
    // str = str.replaceAll('\r', '\\newline'); // IE8 textarea中的换行是\r
    str = str.replaceAll('"', '\\quot');
    str = str.replaceAll("'", '\\danyinhao'); // 不能用singlequot，因为quot会先被替换掉
    console.log('str2', str);
    return str;
  }

  function decodeLinkStr(str) {
    if (!str) return '';
    if (!str.trim()) return '';
    str = str.replaceAll('\\\\semicolon', ';');
    str = str.replaceAll('\\semicolon', ';');
    // 在经过designFlowChar.vue中转换\及eval后，semicolon左侧的反斜杠丢了，但老版无此问题
    str = str.replaceAll('semicolon', ';');
    str = str.replaceAll('\\\\colon', ':');
    str = str.replaceAll('\\colon', ':');
    str = str.replaceAll('colon', ':');

    str = str.replaceAll('\\\\comma', ',');
    str = str.replaceAll('\\comma', ',');
    str = str.replaceAll('comma', ',');

    str = str.replaceAll('\\newline', '\n');
    str = str.replaceAll('\\\\quot', '"');
    str = str.replaceAll('\\quot', '"');
    str = str.replaceAll('quot', '"');

    str = str.replaceAll('\\\\danyinhao', "'");
    str = str.replaceAll('\\danyinhao', "'");
    str = str.replaceAll('danyinhao', "'");

    console.log('decodeLinkStr', str);
    return str;
  }

  function SetSelectedLinkProperty(propItem, propValue) {
    var myflow = $.myflow;
    const curLink = useFlow.curLink;
    console.log('curLink2', curLink);
    var _o = myflow.getPaths()[curLink.getId()];
    if (!_o) {
      // createMessage.warn('连线不存在');
      return;
    }
    const newPropValue = propValue ? propValue : '';
    _o.setProp(propItem, newPropValue);

    var desc = _o.getPropVal('desc');
    var expireHour = _o.getPropVal('expireHour');
    if (expireHour != '') {
      _o.setText(desc + '    ' + expireHour + ' ' + myflow.config.expireUnit);
    } else {
      _o.setText(desc);
    }

    // console.log(_o);
  }

  //选择角色
  const handleSelect = () => {
    handleSelectRole();
  };

  //清空
  const handleSelectClear = () => {
    dataRef.value.depts = '';
    dataRef.value.deptNames = '';
  };

  const [registerModalSelectRole, { openModal: openSelectRole }] = useModal();
  //选择角色
  const handleSelectRole = () => {
    console.log('选择角色');
    let targetKeys = [];
    if (dataRef.value.nodeMode == 0) {
      targetKeys = dataRef.value?.userName ? dataRef.value.userName.split(',') : [];
    }
    openSelectRole(true, {
      record: {
        targetKeys,
      },
    });
  };
  //选择角色回调
  const handleSuccessSelectRole = ({ codes, codeTexts }) => {
    console.log('选择角色回调', { codes, codeTexts });
    dataRef.value.depts = codes;
    dataRef.value.deptNames = codeTexts;
    // const record = getFieldsValue();
    // console.log('record', record);
    // dataRef.value.relateRoleToOrganization = record.relateRoleToOrganization;
    // if (record.relateRoleToOrganization) {
    //   if (codes.indexOf(',') != -1) {
    //     dataRef.value.relateRoleToOrganization = false;
    //     createMessage.warning('多个角色被选择，角色关联已经被取消！');
    //   }
    // }
    // setFieldsValue({
    //   relateRoleToOrganization: dataRef.value.relateRoleToOrganization,
    // });
    // setSpanMode('角色', dataRef.value.userRealName, '0');
  };

  const [registerModalConfigrationCombination, { openModal: openConfiguration }] = useModal();
  //组合条件配置
  const handleConfiguration = () => {
    openConfiguration(true, {
      fields: mockData.value,
      formCode: props.formCode,
      list: dataRef.value.linkList,
    });
  };
  //配置回调
  const handleSuccessConfigrationCombination = (val, list) => {
    dataRef.value.hiddenCondition = val;
    dataRef.value.linkList = list;
  };

  // 设计器
  const [registerModalDesignIframe, { openModal: openDesignIframe, closeModal }] = useModal();

  //设计器打开
  const handleDesignIframe = () => {
    const record = getFieldsValue();
    openDesignIframe(true, {
      formCode: props.formCode,
      scriptStr: record.nodeScript,
    });
  };
  //设计器回调
  const handleSuccessDesignIframe = (value) => {
    dataRef.value.nodeScript = value;
    setFieldsValue({ nodeScript: dataRef.value.nodeScript });
  };

  const ifrmRef = ref<any>(null);
  let ideUrl = 'script_frame.jsp';
  const onMessage = (e) => {
    var d = e.data;
    var data = d.data;
    var type = d.type;
    if (type == 'setScript') {
      console.log('onMessage data', data);
      dataRef.value.depts = '';
      dataRef.value.deptNames = data;
      // setFieldsValue({ nodeScript: dataRef.value.nodeScript });
      if (d.cwsToken != null) {
        let cwsToken = d.cwsToken;
        ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
      }
      closeModal();
    } else if (type == 'getScript') {
      let serverInfo = userStore.getServerInfo;
      let data = {
        type: 'openerScript',
        version: serverInfo.version,
        spVersion: serverInfo.spVersion,
        scene: 'flow.condition',
        data: dataRef.value.deptNames ? dataRef.value.deptNames : '',
      };
      // window.postMessage(data, '*');
      unref(ifrmRef)?.doPostMessage(data);
    } else if (type == 'setCwsToken') {
      let cwsToken = d.cwsToken;
      ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
    }
  };

  if (window.addEventListener) {
    // all browsers except IE before version 9
    window.addEventListener('message', onMessage, false);
  }
  onUnmounted(() => {
    console.log('PathEdit-onUnmounted');
    window.removeEventListener('message', onMessage, false);
  });
</script>
<style lang="less" scoped></style>
